package com.bhs.sansong.ui.findLogistics;

import static com.umeng.pagesdk.PageManger.getApplicationContext;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.aip.asrwakeup3.core.mini.AutoCheck;
import com.baidu.aip.asrwakeup3.core.util.AuthUtil;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.bhs.sansong.R;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseFragment;
import com.bhs.sansong.base.Constants;
import com.bhs.sansong.bean.PhoneticResul;
import com.bhs.sansong.bean.SpecialLineData;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.dialog.BottomVoiceDialog;
import com.bhs.sansong.ui.dialog.CityPickerDialog;
import com.bhs.sansong.ui.dialog.MyClickListener2;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

import com.baidu.speech.EventListener;

/**
 * 首页搜索物流公司
 */
public class SearchLogisticsFragment extends BaseFragment implements View.OnClickListener, NetCallBack, EventListener {

    private TextView mTvStartCity;
    private TextView mTvEndCity;
    private LinearLayout mLlClearRecord;
    private RecyclerView mRvList;
    private TextView mTvClearRecord;
    private TextView mTvSpecialLine;
    private TextView mTvCompany;
    private LinearLayout mLlCity;
    private EditText mEtCompanyName;
    private View mViewLine;
    private Button mBtnCheckOrder;
    private String btnText = "搜索专线";
    private LinearLayout mLlVoiceSearch;
    private EventManager asr;
    private boolean logTime = true;

    protected boolean enableOffline = false; // 测试离线命令词，需要改成true

    public static SearchLogisticsFragment newInstance() {
        return new SearchLogisticsFragment();
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_search_logistics;
    }

    @Override
    public void initView(View root) {
        mTvSpecialLine = root.findViewById(R.id.tv_special_line);
        mTvCompany = root.findViewById(R.id.tv_company);
        mTvStartCity = root.findViewById(R.id.tv_start_city);
        mTvEndCity = root.findViewById(R.id.tv_end_city);
        mLlVoiceSearch = root.findViewById(R.id.ll_voice_search);
        mLlClearRecord = root.findViewById(R.id.ll_clear_record);
        mRvList = root.findViewById(R.id.rv_list);
        mTvClearRecord = root.findViewById(R.id.tv_clear_record);
        mTvEndCity.setOnClickListener(this);
        mTvEndCity.setOnClickListener(this);
        mTvSpecialLine.setOnClickListener(this);
        mTvCompany.setOnClickListener(this);
        mTvStartCity.setOnClickListener(this);
        mLlCity = root.findViewById(R.id.ll_city);
        mEtCompanyName = root.findViewById(R.id.et_company_name);
        mViewLine = root.findViewById(R.id.view_line);
        mBtnCheckOrder = root.findViewById(R.id.btn_check_order);
        mBtnCheckOrder.setOnClickListener(this);
        root.findViewById(R.id.iv_switchover).setOnClickListener(this);
        // 基于sdk集成1.1 初始化EventManager对象
        asr = EventManagerFactory.create(getContext(), "asr");
        // 基于sdk集成1.3 注册自己的输出事件类
        asr.registerListener(this); //  EventListener 中 onEvent方法

        if (enableOffline) {
            loadOfflineEngine(); // 测试离线命令词请开启, 测试 ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH 参数时开启
        }
    }

    private BottomVoiceDialog voiceDialog;

    @Override
    public void initData() {
        if (Constants.city != null) {
            mTvStartCity.setText(Constants.city);
        }
        mLlVoiceSearch.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (voiceDialog == null) {
                            initPermission();
                            voiceDialog = new BottomVoiceDialog(getContext());
                        }
                        start();
                        voiceDialog.show();
                        voiceDialog.setText("");
                        break;
                    case MotionEvent.ACTION_UP:
                        voiceDialog.dismiss();
                        stop();
                        break;
                    default:
                        break;
                }

                return true;
            }
        });
    }

    /**
     * 开始录音
     */
    private void start() {

        Map<String, Object> params = AuthUtil.getParam();
        String event = null;
        event = SpeechConstant.ASR_START; // 替换成测试的event

        if (enableOffline) {
            params.put(SpeechConstant.DECODER, 2);
        }
        (new AutoCheck(getContext(), new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 100) {
                    AutoCheck autoCheck = (AutoCheck) msg.obj;
                    synchronized (autoCheck) {
                        String message = autoCheck.obtainErrorMessage(); // autoCheck.obtainAllMessage();
                        LogUtils.d(message);
                    }
                }
            }
        }, enableOffline)).checkAsr(params);
        String json = null; // 可以替换成自己的json
        json = new JSONObject(params).toString(); // 这里可以替换成你需要测试的json
        asr.send(event, json, null, 0, 0);
    }

    /**
     * 点击停止按钮
     */
    private void stop() {
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0); //
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_start_city:
                bottomSelectCity();
                break;
            case R.id.tv_end_city:
                bottomSelectCity2();
                break;
            case R.id.tv_special_line:
                mLlCity.setVisibility(View.VISIBLE);
                mEtCompanyName.setVisibility(View.GONE);
                mViewLine.setVisibility(View.GONE);
                mBtnCheckOrder.setText(btnText);
                mTvCompany.setBackground(null);
                mTvCompany.setTypeface(Typeface.DEFAULT);
                mTvSpecialLine.setBackgroundResource(R.drawable.bg_top_white_16);
                mTvSpecialLine.setTypeface(Typeface.DEFAULT_BOLD);
                break;
            case R.id.tv_company:
                mLlCity.setVisibility(View.GONE);
                mEtCompanyName.setVisibility(View.VISIBLE);
                mViewLine.setVisibility(View.VISIBLE);
                mBtnCheckOrder.setText("搜索公司");
                mTvSpecialLine.setBackground(null);
                mTvSpecialLine.setTypeface(Typeface.DEFAULT);
                mTvCompany.setBackgroundResource(R.drawable.bg_top_white_16);
                mTvCompany.setTypeface(Typeface.DEFAULT_BOLD);
                break;
            case R.id.btn_check_order:
                Intent intent = new Intent(getActivity(), LogisticsCompaniesListActivity.class);
                if (mBtnCheckOrder.getText().toString().equals("搜索公司")) {
                    if (TextUtils.isEmpty(mEtCompanyName.getText())) {
                        ToastUtil.show("请输入公司名称");
                        return;
                    }
                    intent.putExtra("companyName", mEtCompanyName.getText().toString());
                } else {
                    if (TextUtils.isEmpty(mTvStartCity.getText())) {
                        ToastUtil.show("请选择起始城市");
                        return;
                    }
                    if (TextUtils.isEmpty(mTvEndCity.getText())) {
                        ToastUtil.show("请选择到达城市");
                        return;
                    }
                    intent.putExtra("startCity", mTvStartCity.getText().toString())
                            .putExtra("endCity", mTvEndCity.getText().toString())
                            .putExtra("end_county", (String) mTvEndCity.getTag());

                }
                intent.putExtra("type", 2);
                startActivity(intent);
                break;
            case R.id.iv_switchover:
                String startCity = mTvStartCity.getText().toString();
                mTvStartCity.setText(mTvEndCity.getText().toString());
                mTvEndCity.setText(startCity);
                getSpecialLineList();
                break;
        }
    }


    private void getSpecialLineList() {
        if (TextUtils.isEmpty(mTvEndCity.getText()) || TextUtils.isEmpty(mTvStartCity.getText())) {
            return;
        }

        Map<String, String> map = new ArrayMap();
        map.put("start_city", mTvStartCity.getText().toString());
        map.put("end_city", mTvEndCity.getText().toString());
        if (!TextUtils.isEmpty((String) mTvEndCity.getTag()) && !mTvEndCity.getTag().equals("全市")) {
            map.put("end_county", (String) mTvEndCity.getTag());
        }
        map.put("page", "1");
        map.put("limit", "1");
        networkRequest(netApi.get_special_line_list(map), this, 999);
    }

    private CityPickerDialog cityPickerDialog;//优惠券

    private void bottomSelectCity() {
        if (cityPickerDialog == null) {
            cityPickerDialog = new CityPickerDialog((BaseActivity) getActivity(), false);
            cityPickerDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    String[] address = info.split(",");
                    mTvStartCity.setText(address[1]);
                    getSpecialLineList();
                }
            });
        }

        cityPickerDialog.show();
        cityPickerDialog.cityPickerReuse.setCity(Constants.city);
    }

    private CityPickerDialog cityPickerDialog2;

    private void bottomSelectCity2() {
        if (cityPickerDialog2 == null) {
            cityPickerDialog2 = new CityPickerDialog((BaseActivity) getActivity(), false);
            cityPickerDialog2.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    String[] address = info.split(",");
                    mTvEndCity.setText(address[1]);
                    mTvEndCity.setTag(address[2]);
                    getSpecialLineList();
                }
            });
        }

        cityPickerDialog2.show();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 999) {
            SpecialLineData specialLineData = new Gson().fromJson(json, SpecialLineData.class);
            if (specialLineData.isStatus()) {
                btnText = String.format("共%s条 查看", specialLineData.getData().getTotal_count());
                mBtnCheckOrder.setText(btnText);
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    public void onEvent(String name, String params, byte[] data, int offset, int length) {
        String logTxt = "name: " + name;

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            // 识别相关的结果都在这里
            if (params == null || params.isEmpty()) {
                return;
            }
            PhoneticResul phoneticResul = new Gson().fromJson(params, PhoneticResul.class);
            voiceDialog.setText(phoneticResul.getBest_result());
            if (params.contains("\"nlu_result\"")) {
                // 一句话的语义解析结果
                if (length > 0 && data.length > 0) {
                    logTxt += ", 语义解析结果：" + new String(data, offset, length);
                }
            } else if (params.contains("\"partial_result\"")) {
                // 一句话的临时识别结果
                logTxt += ", 临时识别结果：" + params;
            } else if (params.contains("\"final_result\"")) {
                // 一句话的最终识别结果
                logTxt += ", 最终识别结果：" + params;
                String best_result = phoneticResul.getBest_result();
                best_result = best_result.replace("。", "");
                String[] results = best_result.split("到");
                if (results.length == 2) {
                    if(!results[0].contains("市")){
                        results[0]=results[0]+"市";
                    }
                    if(!results[1].contains("市")){
                        results[1]=results[1]+"市";
                    }
                    Intent intent = new Intent(getActivity(), LogisticsCompaniesListActivity.class);
                    intent.putExtra("startCity", results[0])
                            .putExtra("endCity", results[1]);
                    intent.putExtra("type", 2);
                    startActivity(intent);
                }
            } else {
                // 一般这里不会运行
                logTxt += " ;params :" + params;
                if (data != null) {
                    logTxt += " ;data length=" + data.length;
                }
            }
        } else {
            // 识别开始，结束，音量，音频数据回调
            if (params != null && !params.isEmpty()) {
                logTxt += " ;params :" + params;
            }
            if (data != null) {
                logTxt += " ;data length=" + data.length;
            }
        }


        LogUtils.d(logTxt);
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String permissions[] = {Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getContext(), perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.

            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(getActivity(), toApplyList.toArray(tmpList), 123);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        asr.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 基于SDK集成4.2 发送取消事件
        asr.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0);
        if (enableOffline) {
            unloadOfflineEngine(); // 测试离线命令词请开启, 测试 ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH 参数时开启
        }

        // 基于SDK集成5.2 退出事件管理器
        // 必须与registerListener成对出现，否则可能造成内存泄露
        asr.unregisterListener(this);
    }

    /**
     * enableOffline为true时，在onDestory中调用，与loadOfflineEngine对应
     * 基于SDK集成5.1 卸载离线资源步骤(离线时使用)
     */
    private void unloadOfflineEngine() {
        asr.send(SpeechConstant.ASR_KWS_UNLOAD_ENGINE, null, null, 0, 0); //
    }

    /**
     * enableOffline设为true时，在onCreate中调用
     * 基于SDK离线命令词1.4 加载离线资源(离线时使用)
     */
    private void loadOfflineEngine() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put(SpeechConstant.DECODER, 2);
        params.put(SpeechConstant.ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH, "assets://baidu_speech_grammar.bsg");
        asr.send(SpeechConstant.ASR_KWS_LOAD_ENGINE, new JSONObject(params).toString(), null, 0, 0);
    }
}